package models

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type Archives struct {
	Id           int64
	DepartmentId int64
	Number       string
	Openid       string
	Integral     int64
	Mobile       string
	Realname     string
	Pinyin       string
	Sex          string
	Age          int
	Birthday     string
	Address      string
	Street       string
	Idcard       string
	CreatedAt    int64
	UpdatedAt    int64
	CreatedBy    string
	UpdatedBy    string
	Status       int
	SchoolId     int64
	SchoolName   string
	PayFrequency int64
	Optometry    []*Optometry `orm:"reverse(many)"`
}

type ArchivesQueryParam struct {
	BaseQueryParam
	Filter       string
	DepartmentId int64
	Deps         []string
}

func (a *Archives) TableName() string {
	return ArchivesTableName()
}

func ArchivesTableName() string {
	return TableName("ar_archives")
}

/**
* 添加档案
 */
func ArchivesAdd(a *Archives) (int64, error) {
	a.CreatedAt = time.Now().Unix()
	a.UpdatedAt = time.Now().Unix()
	a.Status = 1
	return orm.NewOrm().Insert(a)
}

//修改档案
func (a *Archives) ArchivesEdit(fields ...string) error {
	a.UpdatedAt = time.Now().Unix()
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

//单条档案查询
func GetArchivesById(id int64) (*Archives, error) {
	r := new(Archives)
	r.Id = id
	err := orm.NewOrm().Read(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//单条档案查询
func GetArchivesByNumber(number string) (*Archives, error) {
	r := new(Archives)
	err := orm.NewOrm().QueryTable(ArchivesTableName()).Filter("Number", number).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//查询分页数据
func ArchivesPageList(params *ArchivesQueryParam) ([]*Archives, int64) {
	query := orm.NewOrm().QueryTable(ArchivesTableName())
	data := make([]*Archives, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if len(params.Filter) > 0 {
		cond = cond.Or("mobile__contains", params.Filter).Or("pinyin__contains", params.Filter).Or("realname__contains", params.Filter).Or("number", params.Filter)
	}
	if len(params.Deps) > 0 {
		//cond = cond.And("DepartmentId__in", params.Deps)
	}
	query = query.SetCond(cond)

	query = query.Filter("status", 1)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total

}

//获取查询条件的记录数
func ArchivesFilterCount(params *ArchivesQueryParam) int64 {

	query := orm.NewOrm().QueryTable(ArchivesTableName())
	if params.Filter != "" {
		query = query.Filter("mobile", params.Filter)
	}
	query = query.Filter("status", 1)

	if count, err := query.Count(); err != nil {
		return 0
	} else {
		return count
	}
}

//删除档案，且同步删除验光资料
func ArchivesDelete(id int64, depid int64) error {

	ar, err := GetArchivesById(id)
	if err != nil {
		return err
	}
	if ar.DepartmentId != depid {
		return errors.New("找不到档案信息")
	}
	//删除主档案
	ar.Status = 0
	if err := ar.ArchivesEdit("status"); err != nil {
		return err
	}

	//同步删除验光资料
	o := orm.NewOrm().QueryTable(OptometryTableName()).Filter("archives_id", id)
	_, err2 := o.Update(orm.Params{"status": 0})

	if err2 != nil {
		return err2
	}

	return nil
}

func queryArchivesTimeSoltSeter(curuser BackendUser, starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(ArchivesTableName())

	cond := orm.NewCondition()
	cond = cond.And("status", 1).AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	query = query.SetCond(cond)
	query = query.Filter("department_id", curuser.DepartmentId)
	return query
}

//按时间段获取档案数据
func QueryArchivesTimeSoltSeter(curuser BackendUser, starttime, endtime int64) []*Archives {

	data := make([]*Archives, 0)

	queryArchivesTimeSoltSeter(curuser, starttime, endtime).All(&data)

	return data
}

//按时间段获取验光count
func QueryArchivesTimeSoltSeterCount(curuser BackendUser, starttime, endtime int64) int64 {

	count, _ := queryArchivesTimeSoltSeter(curuser, starttime, endtime).Count()

	return count
}
